<template>
    <Popup @register="registerPopup">
        <template #content>
            <BasicForm @register="register" />
        </template>
    </Popup>
</template>

<script setup lang='ts'>
import { Popup, usePopup } from '@/components/popup/index';
import { Modal } from 'ant-design-vue';
import type { FormSchema } from '@/components/form';
// 引用表单组件及配置文件
import { BasicForm, useForm } from '@/components/form/index';

const schemaList = ref<Recordable[]>([]);

const formProps = reactive<Recordable>({});

// 表单配置
const [register, { setProps, validateFields }] = useForm({
    labelWidth: 300,
    layout: 'horizontal',
    schemas: [],
    showResetButton: false,
    showSubmitButton: false,
});

// 弹出层属性配置
const [registerPopup, { openPopup, closePopup }] = usePopup({
    type: 'Modal', // 弹出层类型
    title: '预览',
    maskClosable: true,
    width: 750,
    confrimButton: async() => {
        try { 
            await validateFields();
            Modal.success({
                title: '表单校验必填项通过！',
                okText: '关闭窗口',
                onOk: () => close(),
            });
        }catch(err) {
            console.error('校验失败：', err);
            Modal.error({ title: '表单校验必填项未通过，请检查！' });
        }
    },
});

const open = async(schema:Recordable[], config: Recordable) => {
    schemaList.value = schema || [];
    Object.assign(formProps, config);
    await openPopup();
    await setProps({
        labelWidth: formProps?.labelWidth || 300,
        layout: formProps?.layout || 'horizontal',
        schemas: unref(schemaList),
        showResetButton: false,
        showSubmitButton: false,
    });
};

defineExpose({ close, open });
</script>